/*
 * MainActivity.java
 * business
 *
 * Created by ChenTao on 2017/2/28.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;

import com.yidiandao.business.R;
import com.yidiandao.business.base.BaseActivity;
import com.yidiandao.business.constant.Common;
import com.yidiandao.business.constant.Intents;
import com.yidiandao.business.constant.Preferences;
import com.yidiandao.business.data.event.UnZipBottomBarIconFinishEvent;
import com.yidiandao.business.data.model.DiscoveryModel;
import com.yidiandao.business.data.model.HomeModel;
import com.yidiandao.business.data.model.ShoppingCartModel;
import com.yidiandao.business.data.model.UserModel;
import com.yidiandao.business.ui.main.category.CategoryFragment;
import com.yidiandao.business.ui.main.category.CategoryPresenter;
import com.yidiandao.business.ui.main.discovery.DiscoveryFragment;
import com.yidiandao.business.ui.main.discovery.DiscoveryPresenter;
import com.yidiandao.business.ui.main.home.HomeFragment;
import com.yidiandao.business.ui.main.home.HomePresenter;
import com.yidiandao.business.ui.main.shoppingcart.ShoppingCartFragment;
import com.yidiandao.business.ui.main.shoppingcart.ShoppingCartPresenter;
import com.yidiandao.business.ui.main.usercenter.UserCenterFragment;
import com.yidiandao.business.ui.main.usercenter.UserCenterPresenter;
import com.yidiandao.business.ui.widget.view.BottomBar;
import com.yidiandao.business.utils.ActivityStack;
import com.yidiandao.business.utils.BuglyUtils;
import com.yidiandao.business.utils.PreferenceUtils;
import com.yidiandao.business.utils.PushUtils;
import com.yidiandao.business.utils.UIUtils;
import com.yidiandao.business.utils.UmengUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.sharesdk.framework.ShareSDK;

public class MainActivity extends BaseActivity {

    private static final String LAST_TAB_TAG = "last_tab_tag";

    private HomeFragment mHomeFragment;

    private CategoryFragment mCategoryFragment;

    private DiscoveryFragment mDiscoveryFragment;

    private ShoppingCartFragment mShoppingCartFragment;

    private UserCenterFragment mUserCenterFragment;

    /**
     * 最后一个Fragment
     */
    private Fragment mLastFragment;

    private HomePresenter mHomePresenter;

    private CategoryPresenter mCategoryPresenter;

    private DiscoveryPresenter mDiscoveryPresenter;

    private ShoppingCartPresenter mShoppingCartPresenter;

    private UserCenterPresenter mUserCenterPresenter;

    private BottomBar mBottomBar;

    //    private AlertDialog mDialog;

    private long mBackPressedTime;

    private String currentTag;

//    private boolean lastClickShoppingCartAndUnLogin;

    public static void actionStart(Activity activity) {
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
    }

    /**
     * MainActivity已经启动之后的跳转,会走onNewIntent方法.
     *
     * @param switchFragmentTag 指定ManiActivity选中哪一个页面
     */
    public static void actionStart(Activity activity, String switchFragmentTag) {
        Intent intent = new Intent(activity, MainActivity.class);
        intent.putExtra(Intents.EXTRA_SWITCH_TAG, switchFragmentTag);
        activity.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBottomBar = (BottomBar) findViewById(R.id.bottom_bar);

        // 切换Fragment
        mBottomBar.setOnBottomBarItemClickListener(new BottomBar.OnBottomBarItemClickListener() {
            @Override
            public boolean onBottomBarItemClick(int position) {
                return switchTab(position);
            }
        });

        // 先更新底部的BottomBar图标
        mBottomBar.updateBottomBarStateImages();

        if (savedInstanceState != null) {
            // 异常情况下重新赋值
            restoreAllTabs(savedInstanceState);
        } else {
            // 极光推送
            initJPush();

            switchTab(BottomBar.HOME);
        }
    }

    /**
     * 异常情况下恢复MainActivity时，重置所有Tab的数据
     */
    private void restoreAllTabs(Bundle savedInstanceState) {

        FragmentManager fragmentManager = getSupportFragmentManager();

        // 根据tag找到所有的Fragment
        mHomeFragment = (HomeFragment) fragmentManager.findFragmentByTag(HomeFragment.TAG);
        mCategoryFragment = (CategoryFragment) fragmentManager.findFragmentByTag(CategoryFragment.TAG);
        mDiscoveryFragment = (DiscoveryFragment) fragmentManager.findFragmentByTag(DiscoveryFragment.TAG);
        mShoppingCartFragment = (ShoppingCartFragment) fragmentManager.findFragmentByTag(ShoppingCartFragment.TAG);
        mUserCenterFragment = (UserCenterFragment) fragmentManager.findFragmentByTag(UserCenterFragment.TAG);

        // 重新创建Presenter与View关联
        if (mHomeFragment != null) {
            mHomePresenter = new HomePresenter(mHomeFragment, new HomeModel(), new UserModel());
        }

        if (mCategoryFragment != null) {
            mCategoryPresenter = new CategoryPresenter(mCategoryFragment);
        }

        if (mDiscoveryFragment != null) {
            mDiscoveryPresenter = new DiscoveryPresenter(mDiscoveryFragment, new DiscoveryModel());
        }

        if (mShoppingCartFragment != null) {
            mShoppingCartPresenter = new ShoppingCartPresenter(mShoppingCartFragment, new ShoppingCartModel(), new UserModel());
        }

        if (mUserCenterFragment != null) {
            mUserCenterPresenter = new UserCenterPresenter(mUserCenterFragment);
        }

        String savedTag = savedInstanceState.getString(LAST_TAB_TAG);

        if (savedTag != null) {
            reChooseTab(fragmentManager, savedTag);
        }
    }

    /**
     * 重新选择Tab
     */
    private void reChooseTab(FragmentManager fragmentManager, String savedTag) {
        mLastFragment = fragmentManager.findFragmentByTag(savedTag);
        if (HomeFragment.TAG.equals(savedTag)) {
            toSwitchFragment(BottomBar.HOME);
        } else if (CategoryFragment.TAG.equals(savedTag)) {
            toSwitchFragment(BottomBar.CATEGORY);
        } else if (DiscoveryFragment.TAG.equals(savedTag)) {
            toSwitchFragment(BottomBar.DISCOVERY);
        } else if (ShoppingCartFragment.TAG.equals(savedTag)) {
            toSwitchFragment(BottomBar.SHOPPING_CART);
        } else {
            toSwitchFragment(BottomBar.USER_CENTER);
        }
    }

    private void initJPush() {
        boolean isJPushSwitchOpen = PreferenceUtils.getBoolean(UIUtils.getContext(), Preferences.JPUSH_SWITCH, true, true);
        if (isJPushSwitchOpen) {
            PushUtils.resumePush(UIUtils.getContext());
        } else {
            PushUtils.stopPush(UIUtils.getContext());
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // SingleTask模式 startActivity会走该方法
        String switchTag = intent.getStringExtra(Intents.EXTRA_SWITCH_TAG);

        // 指定选中哪一个页面
        if (HomeFragment.TAG.equals(switchTag)) {
            // 到主页随便逛逛
            randomToHome();
        } else if (ShoppingCartFragment.TAG.equals(switchTag)) {
            // 去购物车前先检查用户是否登录,未登录就去登录页面
            // 不再选中购物车tab
//            if (!PriceUtils.isLogin()) {
//                LoginActivity.actionStart(this);
//                return;
//            }

            // 去购物车
            toSwitchFragment(BottomBar.SHOPPING_CART);
        }
    }

    public void randomToHome() {
        toSwitchFragment(BottomBar.HOME);
        mHomeFragment.smoothToTop();
    }

    /**
     * 跳转到指定页面
     */
    public void toSwitchFragment(@BottomBar.Position int position) {
        if (switchTab(position)) {
            // 根据返回值决定是否选中BottomBar的指定页面，避免未登录时出现bug
            mBottomBar.setSelected(position);
            if (position == BottomBar.SHOPPING_CART) {
                // 点击跳转到购物车页面需要刷新
                setRefreshShoppingCart();
            }
        }
    }

    private boolean switchTab(@BottomBar.Position int position) {

        switch (position) {
            case BottomBar.HOME:
                // 首页
                if (mHomeFragment == null) {
                    mHomeFragment = HomeFragment.getInstance();
                }
                if (mHomePresenter == null) {
                    mHomePresenter = new HomePresenter(mHomeFragment, new HomeModel(), new UserModel());
                }

                changeFragment(mHomeFragment, HomeFragment.TAG);
                break;

            case BottomBar.CATEGORY:
                // 分类页
                if (mCategoryFragment == null) {
                    mCategoryFragment = CategoryFragment.getInstance();
                }

                if (mCategoryPresenter == null) {
                    mCategoryPresenter = new CategoryPresenter(mCategoryFragment);
                }
                changeFragment(mCategoryFragment, CategoryFragment.TAG);
                break;

            case BottomBar.DISCOVERY:
                // 发现页
                if (mDiscoveryFragment == null) {
                    mDiscoveryFragment = DiscoveryFragment.getInstance();
                }
                if (mDiscoveryPresenter == null) {
                    mDiscoveryPresenter = new DiscoveryPresenter(mDiscoveryFragment, new DiscoveryModel());
                }
                changeFragment(mDiscoveryFragment, DiscoveryFragment.TAG);
                break;

            case BottomBar.SHOPPING_CART:
                // 需要检查用户是否登录，如果未登录，则去登录页面
//                if (!PriceUtils.isLogin()) {
//                    LoginActivity.actionStart(this);
//
//                    // 加入该标记：方便未登陆时选择购物车页面，登录后回到购物车页面
//                    // 用户点击了购物车，并且没有没有登录
//                    // 上一次点击了购物车并且未登录
//                    lastClickShoppingCartAndUnLogin = true;
//                    return false;
//                }

                // 点击跳转到购物车页面需要刷新
                setRefreshShoppingCart();

                // 购物车
                if (mShoppingCartFragment == null) {
                    mShoppingCartFragment = ShoppingCartFragment.getInstance();
                }
                if (mShoppingCartPresenter == null) {
                    mShoppingCartPresenter = new ShoppingCartPresenter(mShoppingCartFragment, new ShoppingCartModel(), new UserModel());
                }
                changeFragment(mShoppingCartFragment, ShoppingCartFragment.TAG);
                break;

            case BottomBar.USER_CENTER:
                // 个人中心
                if (mUserCenterFragment == null) {
                    mUserCenterFragment = UserCenterFragment.getInstance();
                }
                if (mUserCenterPresenter == null) {
                    mUserCenterPresenter = new UserCenterPresenter(mUserCenterFragment);
                }
                changeFragment(mUserCenterFragment, UserCenterFragment.TAG);
                break;
        }

        return true;
    }

    private void setRefreshShoppingCart() {
        // 点击跳转到购物车页面需要刷新
        PreferenceUtils.setBoolean(UIUtils.getContext(), Preferences.REFRESH_SHOPPING_CART, true, true);
    }

    @Override
    protected void initFragment() {
    }

    @Override
    protected void initPresenter() {
    }

    private void changeFragment(Fragment addFragment, String tag) {

        currentTag = tag;

        if (mLastFragment == addFragment) {
            return;
        }

        // 开始事物
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (mLastFragment != null) {
            // 如果最后一次加载的不是现在要加载的Fragment，那么将最后一次加载的移出
            fragmentTransaction.detach(mLastFragment);
        }
        if (addFragment == null) {
            return;
        }

        if (!addFragment.isAdded()) {
            // 如果还没有添加，就加上
            fragmentTransaction.add(R.id.container_main, addFragment, tag);
        }

        if (addFragment.isDetached()) {
            fragmentTransaction.attach(addFragment);
        }

        mLastFragment = addFragment;
        fragmentTransaction.commitAllowingStateLoss();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(LAST_TAB_TAG, currentTag);
    }

//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.tv_dialog_evaluate_agree:
//                toAppMarketActivity();
//                break;
//            case R.id.tv_dialog_evaluate_disagree:
//                SuggestionAndFeedbackActivity.actionStart(this);
//                break;
//            case R.id.tv_dialog_evaluate_refuse:
//                break;
//        }
//        //        mDialog.dismiss();
//    }

//    private void toAppMarketActivity() {
//        try {
//            Uri uri = Uri.parse("market://details?id=" + getPackageName());
//            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(intent);
//        } catch (Exception e) {
//            e.printStackTrace();
//            UIUtils.showToast(getString(R.string.dialog_tip3));
//        }
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出.
     */
    private void exit() {
        /* 连按两次退出 */
        long currentTime = System.currentTimeMillis();
        if (currentTime - mBackPressedTime > Common.EXIT_INTERVAL) {
            UIUtils.showToast(UIUtils.getString(R.string.exit_toast));
            mBackPressedTime = currentTime;
        } else {
            ActivityStack.finishAllActivity();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            UmengUtils.onKillProcess();
            System.exit(0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UnZipBottomBarIconFinishEvent event) {
        mBottomBar.updateBottomBarStateImages();
    }

    /**
     * 获取当前所在页面
     */
    public String getCurrentTag() {
        return currentTag;
    }

//    @Override
//    protected void onStart() {
//        super.onStart();
//        if (lastClickShoppingCartAndUnLogin && PriceUtils.isLogin()) {
//            // 上次是为登录，并且已经登录才去购物车
//            switchTab(POSITION.SHOPPING_CART);
//            mBottomBar.setSelected(POSITION.SHOPPING_CART);
//
//            // 基于为登录-->登录后去购物车只执行一次
//            lastClickShoppingCartAndUnLogin = false;
//        }
//    }

    @Override
    protected void onResume() {
        super.onResume();
        BuglyUtils.setAppBackground(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BuglyUtils.setAppBackground(true);
    }
}
